Menu OmegaForms.Net

JavaScript: Control Structures

Control structures are fundamental constructs in programming languages that allow you to control the flow of your code. They enable you to make decisions based on conditions, execute code repeatedly, and manage complex logic. In JavaScript, the most common control structures are conditional statements (if-else, switch), loops (for, while, do-while), and exception handling (try-catch-finally).

  1. Conditional Statements: These structures allow you to execute code based on whether a specific condition is true or false.
  • If-else statement: This is a basic conditional statement that tests a condition and executes a block of code if the condition is true; otherwise, it executes an optional else block.
javascript
let age = 18; if (age >= 18) { console.log("You are eligible to vote."); } else { console.log("You are not eligible to vote."); }
  • If-else-if ladder: This structure is used when multiple conditions need to be tested.
javascript
let grade = 85; if (grade >= 90) { console.log("A"); } else if (grade >= 80) { console.log("B"); } else if (grade >= 70) { console.log("C"); } else if (grade >= 60) { console.log("D"); } else { console.log("F"); }
  • Ternary Operator (Conditional Operator): This is a shorthand for an if-else statement, taking three operands. It returns the value of the second operand if the condition is true, and the value of the third operand if the condition is false.
javascript
let age = 18; let canVote = age >= 18 ? "Yes" : "No";
  • Switch statement: This structure is used when you have multiple cases to test against a single expression. It is more concise and easier to read than a long if-else-if ladder.
javascript
let day = 3; let dayName; switch (day) { case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thursday"; break; case 5: dayName = "Friday"; break; case 6: dayName = "Saturday"; break; case 7: dayName = "Sunday"; break; default: dayName = "Invalid day"; } console.log(dayName); // "Wednesday"
  1. Loops: These structures allow you to execute a block of code repeatedly until a certain condition is met.
  • For loop: This loop has three parts: the initialization, the condition, and the final expression (which typically increments or decrements the loop counter). The loop executes the code block as long as the condition is true.
javascript
for (let i = 0; i < 5; i++) { console.log(i); // 0, 1, 2, 3, 4 }
  • While loop: This loop checks the condition before executing the code block. If the condition is true, the code block is executed, and the process repeats.
javascript
let i = 0; while (i < 5) { console.log(i); // 0, 1, 2, 3, 4 i++; }
  • Do-while loop: This loop executes the code block at least once and then checks the condition. If the condition is true, the code block is executed again, and the process repeats.

javascript
let i = 0; do { console.log(i); // 0, 1, 2, 3, 4 i++; } while (i < 5);
  • For-of loop: This loop is used to iterate over iterable objects like arrays, strings, and other data structures. It assigns each value in the iterable to a variable and executes the code block.
javascript
let array = [1, 2, 3, 4, 5]; for (let value of array) { console.log(value); // 1, 2, 3, 4, 5 }
  • For-in loop: This loop is used to iterate over the enumerable properties of an object. It assigns each property key to a variable and executes the code block.
javascript
let person = { name: "Alice", age: 30, city: "New York" }; for (let key in person) { console.log(`${key}: ${person[key]}`); // "name: Alice", "age: 30", "city: New York" }
  1. Exception Handling: This structure is used to catch and handle errors gracefully, without stopping the execution of the entire program.
  • Try-catch statement: The try block contains the code that might throw an exception. If an exception occurs, the catch block is executed, allowing you to handle the error appropriately.
javascript
try { let result = 10 / 0; // Division by zero console.log(result); } catch (error) { console.log("An error occurred:", error.message); }
  • Try-catch-finally statement: The finally block is optional and contains code that is always executed, regardless of whether an exception occurs or not.
javascript
try { let result = 10 / 2; console.log(result); } catch (error) { console.log("An error occurred:", error.message); } finally { console.log("This code will always run."); }

Control structures are essential building blocks for creating complex programs and managing the flow of your code. By understanding and effectively using conditional statements, loops, and exception handling, you can create more robust and efficient JavaScript applications.